package com.ihr360.authority.sharing.controller;

import com.ihr360.authority.sharing.model.request.SimpleAuthUserResourceReq;
import com.ihr360.authority.sharing.model.vo.SimpleAuthUserResourceVo;
import com.ihr360.authority.sharing.service.AuthUserResourceService;
import com.ihr360.authority.sharing.util.BizModelUtil;
import com.ihr360.commons.entity.AuthUserInfo;
import com.ihr360.commons.lang.CollectionUtils;
import com.ihr360.shared.advice.response.DisableResponseAdvice;
import com.ihr360.validation.ValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/authority")
@DisableResponseAdvice
public class AuthUserResourceController {
    @Autowired
    private AuthUserResourceService authUserResourceService;

    @GetMapping(value = "/getResourceUsers")
    public List<SimpleAuthUserResourceVo> getResourceUsers(@RequestParam(value = "companyId") String companyId,
                                                           @RequestParam(value = "bizModel") String bizModelAlias,
                                                           @RequestParam(value = "resourceId") String resourceId) {
        return authUserResourceService.getResourceUsers(companyId, BizModelUtil.getBizModel(bizModelAlias), resourceId);
    }

    @PostMapping(value = "/saveUsers")
    public void getResourceUsers(AuthUserInfo authUserInfo,
                                 @RequestParam(value = "bizModel") String bizModelAlias,
                                 @RequestParam(value = "resourceId") String resourceId,
                                 @RequestBody SimpleAuthUserResourceReq resourceReq) {
        String bizModel = BizModelUtil.getBizModel(bizModelAlias);
        boolean isOwner = authUserResourceService.checkOwner(authUserInfo.getCompanyId(), bizModel,
                authUserInfo.getUserId(), resourceId);
        if (!isOwner) {
            ValidationUtils.reject(null, "没有资源操作权限");
        }

        if (CollectionUtils.isNotEmpty(resourceReq.getUpdatedUsers())) {
            resourceReq.getUpdatedUsers().forEach(vo -> vo.setBizModel(bizModel));
        }
        authUserResourceService.update(resourceId, resourceReq.getUpdatedUsers(), resourceReq.getDeletedIds());
    }

}